from myelin.server.nodetype.Events import EventHandler
from myelin.server.nodetype.Document import Document

#from myelin.rdf.parsers.sparql.rdflib.serializers.XmlSrx import NewSerializer
from Ft.Rdf.Parsers.Sparql.Serializers.Srx import NewSerializer

from nodetypes import config

class Document(Document):
    
    newSerializer = staticmethod(NewSerializer)
    defaultNsMap = config.DEFAULT_NSMAP
    defaultGraphMethodMap = config.SERVICE_SPARQL_GRAPH_METHOD_DEFAULTS
    
    def createDocument(self, context, source):
        eventData = context.event.data
        method = eventData.params.get('graph-result-method')
        method = method and method[0] or self.defaultGraphMethodMap.get(context.method)
        s = self.newSerializer(
            eventData.results,
            method
        )
        doc, imt = s.serialize(
            None,
            context.server.namespaceMap or self.defaultNsMap,           
            context.preferredEncoding
        )
        if isinstance(doc,str):
            return doc, self.getImt(
                context,
                s.method,
                imt,
                context.preferredEncoding
            )
        else:
            return doc, self.getImt(
                context,
                s.method,
                imt
            )
        

class EventHandler(EventHandler):

    newDocument = Document
    
# cleanup
del config, \
    NewSerializer